package com.onenine.app.adapter;

import android.support.annotation.Nullable;
import android.util.SparseBooleanArray;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.onenine.app.R;
import com.onenine.app.event.RefreshEvent;
import com.onenine.app.model.MemberItem;
import com.onenine.app.utils.DataType;
import com.onenine.app.utils.GlideUtils;
import com.onenine.app.utils.RoleResLoader;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

public class MemberSelectAdapter extends BaseQuickAdapter<MemberItem, BaseViewHolder> {

    private SparseBooleanArray mSelectArray;

    public MemberSelectAdapter(@Nullable List<MemberItem> data) {
        super(R.layout.layout_group_member_mgr_item, data);
        mSelectArray = new SparseBooleanArray();
    }

    @Override
    protected void convert(final BaseViewHolder holder, MemberItem groupMember) {
        ImageView ivAvatar = holder.getView(R.id.iv_avatar);
        GlideUtils.loadCircleAvatar(mContext, ivAvatar, groupMember.getPhoto());
        holder.setText(R.id.tv_name, groupMember.getNickName());
        final CheckBox cvCheck = holder.getView(R.id.cb_select);
        cvCheck.setChecked(mSelectArray.get(holder.getLayoutPosition()));
        updateCheckDrawable(cvCheck);
        holder.getConvertView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean nextSelect = mSelectArray.get(holder.getLayoutPosition());
                cvCheck.setChecked(!nextSelect);
                updateCheckDrawable(cvCheck);
                mSelectArray.put(holder.getLayoutPosition(), !nextSelect);
                updateConfirmCount();
            }
        });
    }

    /**
     * 更新check状态图
     *
     * @param cvCheck
     */
    private void updateCheckDrawable(CheckBox cvCheck) {
        if (cvCheck.isChecked()) {
            cvCheck.setButtonDrawable(RoleResLoader
                    .getRoleDrawableResourceId(RoleResLoader.DynamicResName.CHECKBOX_STYLE));
        } else {
            cvCheck.setButtonDrawable(null);
        }
    }

    /**
     * 更新选择数量
     */
    private void updateConfirmCount() {
        int count = 0;
        for (int i = 0; i < mSelectArray.size(); i++) {
            if (mSelectArray.valueAt(i)) {
                count++;
            }
        }
        RefreshEvent event = new RefreshEvent(DataType.REFRESH_MEMBER_SELECT_COUNT);
        event.extraInt = count;
        EventBus.getDefault().post(event);
    }

    public SparseBooleanArray getSelectArray() {
        return mSelectArray;
    }

    public void clearSelectArray() {
        mSelectArray.clear();
    }

}
